// 购物车页面
import React from 'react'
import Layout from './Layout'
import { Row, Col, Form, Input, Typography  } from 'antd'
import CartItem from '../core/CartItem'
// 获取存储到本地的产品信息
import { getProduct } from '../../helper/cart'
import { useState, useEffect } from 'react'
import CarBuy from './CarBuy'
const { Title } = Typography

function Cart() {
	const [cart, setCart] = useState([])
	useEffect(() => {
		setCart(getProduct())
	}, []) // eslint-disable-line react-hooks/exhaustive-deps
	
	// 地址存储
	const [address, setAddress] = useState('')
	// 总价格存储
	const [totalPrice, setTotalPrice] = useState(0)

	useEffect(() => {
		let preVal = cart.reduce(function(preVal, currentVal){
			return preVal += currentVal.count * currentVal.price
		},0).toFixed(2)
		setTotalPrice(preVal)
	}, [cart])

	const getAddress = (e) => {
		setAddress(e.target.value);
	}
	return (
		<>
			<Layout title="购物车" subTitle="付款吧,我就是你的了">
				<Row>
					<Col span={18} style={{padding:"0 8px"}}>
						<table style={{ width: '100%' }}>
							<thead className="ant-table-thead" align="center">
								<tr>
									<th className="ant-table-cell">商品封面</th>
									<th className="ant-table-cell">商品名称</th>
									<th className="ant-table-cell">商品价格</th>
									<th className="ant-table-cell">商品分类</th>
									<th className="ant-table-cell" width={100}>商品数量</th>
									<th className="ant-table-cell">操作</th>
								</tr>
							</thead>
							<tbody className="ant-table-tbody">
								{
									cart.map(item => {
										return <CartItem key={item._id} product={item} setCart={setCart} />
									})
								}
							</tbody>
						</table>
					</Col>
					<Col span={6} style={{padding:"0 8px"}}>
						<Form.Item label="收货地址">
							<Input 
								placeholder='请输入收货地址'
								value={address}
								onChange={getAddress}
							/>
						</Form.Item>
						<Title level={5}>总价为: ¥ {totalPrice}</Title>
						<CarBuy totalMount={totalPrice} product={cart} address={address}/>
					</Col>
				</Row>
			</Layout>
		</>
	)
}

export default Cart
